﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

using Peradigm.Framework.Domain.Security;

using Liberty.Domain.CaseManagement;
using Liberty.Domain.GrantManagement;

namespace Liberty.Application.Security
{

    [Serializable]
    public class ViewGrantPrivilege : Privilege
    {
        #region Constants
        public const string
            KEY_GRANT = "Grant",
            KEY_USER  = "CurrentUser";
        #endregion

        #region Event Handlers
        #endregion

        #region Methods
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action">
        /// </param>
        /// <param name="context">
        /// </param>
        /// <returns>
        /// </returns>
        public override bool Equals( Actions action, object context )
        {
            bool areEquivalent = false;
            Dictionary<string, object> contextItems = context as Dictionary<string, object>;
            if( contextItems != null )
            {
                Grant grant = contextItems[KEY_GRANT] as Grant;
                User currentUser = contextItems[KEY_USER] as User;
                CaseVolunteer volunteer = grant.Case.Volunteer;
                areEquivalent = this.CanViewGrant( action, currentUser, volunteer ) ||
                                currentUser.HasPermissionTo( action, typeof( Grant ) );
            }

            return areEquivalent;
        }
        #endregion

        #region Properties
        #endregion

        #region Private Methods
        private bool CanViewGrant( Actions action,User currentUser, CaseVolunteer volunteer )
        {
            return action == Actions.View &&
                   this.HasSameVolunteer( currentUser, volunteer );
        }

        private bool HasSameVolunteer( User currentUser, CaseVolunteer volunteer )
        {
            return ( string.Compare( currentUser.FirstName, volunteer.FirstName, true ) == 0 ) &&
                   ( string.Compare( currentUser.LastName, volunteer.LastName, true ) == 0 );
        }
        #endregion

        #region Private Properties
        #endregion

        #region Construction and Finalization
        public ViewGrantPrivilege( Actions action, object context )
            : base( action, context )
        {
        }
        #endregion

        #region Data Elements
        #endregion
        
    }
}
